package com.cmcc.groupcontacts.firewall.activity;

import java.util.ArrayList;

import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.cmcc.groupcontacts.firewall.activity.strategy.ActivityTitleStrategy;
import com.cmcc.groupcontacts.firewall.adapter.FilterListAdapter;
import com.cmcc.groupcontacts.firewall.business.FilterListBusiness;
import com.cmcc.groupcontacts.firewall.dao.model.CallInfoVO;
import com.cmcc.groupcontacts.firewall.dao.model.FilterListVO;
import com.cmcc.groupcontacts.util.DialogUtil;
import com.cmcc.groupcontacts.util.IntentManager;
import com.cmcc.groupcontacts.util.StringUtil;
import com.cmcc.groupcontacts.util.ValidationUtil;
import com.yinhai.activity.R;

/**
 * 黑白名单Activity
 * 
 * @author
 * 
 */
public class FilterListActivity extends BaseListActivity {
	/** 是否黑名单 */
	public static final String IS_BLACK_LIST = "IsBlack";

	/* 返回码：从本机联系人添加 */
	private static final int REQUEST_CODE_FROM_LOCAL_CONTACTS = 1;
	/* 返回码：从集团联系人添加 */
	private static final int REQUEST_CODE_FROM_GROUP_CONTACTS = 2;

	private boolean isBlackList = true; // 是-黑名单，否-白名单
	private FilterListBusiness filterListBiz;

	private View clickedItem;
	private FilterListVO clickedFilter;

	@Override
	public void setTitleStrategy() {
		titleStrategy = new ActivityTitleStrategy(this);
	}

	@Override
	public void setTitleButtons() {
		// 左边的“返回”按钮
		getLeftLayout().addView(createBackButton());

		// 中间的“黑名单”和“白名单”按钮
		final Button btnBlack = getTitleButton();
		final Button btnWhite = getTitleButton();
		btnBlack.setText("黑名单");
		btnWhite.setText("白名单");
		// btnBlack.setBackgroundResource(R.drawable.sty0_moresent_btnbg_h);
		btnBlack.setBackgroundColor(Color.parseColor("#009DF5"));
		btnBlack.setTextColor(Color.WHITE);

		btnWhite.setBackgroundColor(Color.WHITE);
		btnWhite.setTextColor(Color.parseColor("#009DF5"));

		// btnWhite.setBackgroundResource(R.drawable.sty0_moresent_btnbg);
		btnBlack.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				isBlackList = true;
				// btnBlack.setBackgroundResource(R.drawable.sty0_moresent_btnbg_h);
				// btnWhite.setBackgroundResource(R.drawable.sty0_moresent_btnbg);
				btnBlack.setBackgroundColor(Color.parseColor("#009DF5"));
				btnBlack.setTextColor(Color.WHITE);
				btnWhite.setBackgroundColor(Color.WHITE);
				btnWhite.setTextColor(Color.parseColor("#009DF5"));
				load();
			}
		});
		btnWhite.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				isBlackList = false;
				// btnBlack.setBackgroundResource(R.drawable.sty0_moresent_btnbg);
				// btnWhite.setBackgroundResource(R.drawable.sty0_moresent_btnbg_h);
				btnBlack.setBackgroundColor(Color.WHITE);
				btnBlack.setTextColor(Color.parseColor("#009DF5"));
				btnWhite.setBackgroundColor(Color.parseColor("#009DF5"));
				btnWhite.setTextColor(Color.WHITE);
				load();
			}
		});
		getCenterLayout().addView(btnBlack);
		getCenterLayout().addView(btnWhite);

		// 右边的“新增”按钮
		final ImageButton btnAdd = createAddButton();
		btnAdd.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				clickedItem = null;
				clickedFilter = null;
				btnAdd.showContextMenu();
			}
		});
		getRightLayout().addView(btnAdd);
		registerForContextMenu(btnAdd);
	}

	private Button getTitleButton() {
		Button button = createButton();
		button.setWidth(getDmConverter().DipToPixel(90));
		// button.setHeight(getDmConverter().DipToPixel(25));
		// button.setTextColor(getColor(R.color.text_reverse));
		LinearLayout.LayoutParams params = ((LinearLayout.LayoutParams) button
				.getLayoutParams());
		// params.leftMargin = params.rightMargin = 5;
		button.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.FILL_PARENT));
		button.setPadding(0, getDmConverter().DipToPixel(10), 0,
				getDmConverter().DipToPixel(10));
		button.setLayoutParams(params);
		return button;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.filter_list_activity);

		init();
	}

	private void init() {
		registerForContextMenu(getListView());
		getListView().setOnItemLongClickListener(
				new AdapterView.OnItemLongClickListener() {
					@Override
					public boolean onItemLongClick(AdapterView<?> parent,
							View view, int position, long id) {
						clickedItem = view;
						clickedFilter = (FilterListVO) parent
								.getItemAtPosition(position);
						getListView().showContextMenu();
						return true;
					}
				});
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		clickedItem = v;
		clickedFilter = (FilterListVO) l.getItemAtPosition(position);
		if (clickedFilter.getType() == FilterListVO.TYPE_BLACK
				|| clickedFilter.getType() == FilterListVO.TYPE_WHITE) {
			showFilterEdit();
		} else if (clickedFilter.getType() == FilterListVO.TYPE_BLACK_AREA) {
			showAreaFilter();
		} else {
			showAreaCodeFilter();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();

		load();
	}

	private void load() {
		// 设置无数据时的提示信息
		if (isBlackList) {
			setEmptyText("");
		} else {
			setEmptyText("");
		}

		// 异步加载黑白名单
		new FilterListLoadTask(isBlackList).execute((Void[]) null);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO: 清空操作
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		if (v instanceof ImageButton) {
			if (isBlackList) {
				menu.setHeaderTitle("添加黑名单");
			} else {
				menu.setHeaderTitle("添加白名单");
			}
			menu.add(0, 1, Menu.NONE, "从通话记录添加");
			menu.add(0, 2, Menu.NONE, "从手机联系人添加");
			menu.add(0, 3, Menu.NONE, "从集团联系人添加");
			if (isBlackList) {
				menu.add(0, 4, Menu.NONE, "按区域添加");
				menu.add(0, 5, Menu.NONE, "按区号添加");
			}
			menu.add(0, 6, Menu.NONE, "手动添加");
		} else {
			if (!ValidationUtil.isNullOrEmpty(clickedFilter.getName())) {
				menu.setHeaderTitle(StringUtil.format("{0}({1})",
						clickedFilter.getName(), clickedFilter.getNumber()));
			} else {
				menu.setHeaderTitle(clickedFilter.getNumber());
			}
			menu.add(0, 11, Menu.NONE, "编辑");
			menu.add(0, 12, Menu.NONE, "删除");
			menu.add(0, 13, Menu.NONE, "呼叫");
			menu.add(0, 14, Menu.NONE, "发信息");
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// 黑白名单两边冲突（相同）时会自动覆盖之前的设置
		switch (item.getItemId()) {
		case 1:
			startActivity(new Intent(this, SelectFromCallLogActivity.class)
					.putExtra(IS_BLACK_LIST, isBlackList));
			break;
		case 2:
			startActivity(new Intent(this, SelectContactsLocalActivityNew.class)
			.putExtra(IS_BLACK_LIST, isBlackList));
//			 startActivityForResult(new Intent(this,
//			 SelectContactsLocalActivity.class),
//			 REQUEST_CODE_FROM_LOCAL_CONTACTS);
			break;
		case 3:
			startActivity(new Intent(this, SelectGroupActivityNew.class)
			.putExtra(IS_BLACK_LIST, isBlackList));
			// startActivityForResult(new Intent(this,
			// SelectContactsGroupActivity.class),
			// REQUEST_CODE_FROM_GROUP_CONTACTS);
			break;
		case 4:
			showAreaFilter();
			break;
		case 5:
			showAreaCodeFilter();
			break;
		case 6:
			// TODO: 区分来电和信息拦截
			// TODO: [优化]支持通配符
			showFilterEdit();
			break;
		}

		switch (item.getItemId()) {
		case 11:
			showFilterEdit();
			break;
		case 12:
			clickedItem.findViewById(R.id.btn_delete).performClick();
			break;
		case 13:
			IntentManager.call(this, clickedFilter.getNumber());
			break;
		case 14:
			IntentManager.sms(this, clickedFilter.getNumber(), "");
			break;
		}
		return super.onContextItemSelected(item);
	}

	private void showAreaCodeFilter() {
		final View layout = getLayoutInflater().inflate(
				R.layout.filter_list_area_code, null);
		final TextView editAreaCode = (TextView) layout
				.findViewById(R.id.edit_area_code);

		final boolean isInsert = (clickedFilter == null);
		if (!isInsert) {
			editAreaCode.setText(clickedFilter.getNumber());
		}

		Builder builder = new Builder(this);
		builder.setTitle("区号");
		builder.setView(layout);
		builder.setPositiveButton(R.string.ok,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int arg1) {
						String areaCode = editAreaCode.getText().toString();
						if (ValidationUtil.isNullOrEmpty(areaCode)) {
							Toast.makeText(getBaseContext(), "请输入区号",
									Toast.LENGTH_SHORT).show();
							return;
						}

						if (isInsert) {
							DialogUtil.closeDialog(dialog, true);

							FilterListVO vo = new FilterListVO();
							vo.setCallState(FilterListVO.STATE_BLOCK);
							vo.setSmsState(FilterListVO.STATE_BLOCK);
							vo.setName(areaCode);
							vo.setNumber(areaCode);
							vo.setType(FilterListVO.TYPE_BLACK_AREA_CODE);
							if (filterListBiz.insert(vo) >= 0) {
								load();
								Toast.makeText(getBaseContext(),
										R.string.insert_ok, Toast.LENGTH_SHORT)
										.show();
							} else {
								Toast.makeText(getBaseContext(),
										R.string.insert_fail,
										Toast.LENGTH_SHORT).show();
							}
						} else {
							clickedFilter.setNumber(areaCode);
							clickedFilter.setName(areaCode);
							if (filterListBiz.update(clickedFilter) >= 0) {
								getBaseAdapter().notifyDataSetChanged();
								Toast.makeText(getBaseContext(),
										R.string.insert_ok, Toast.LENGTH_SHORT)
										.show();
							} else {
								Toast.makeText(getBaseContext(),
										R.string.insert_fail,
										Toast.LENGTH_SHORT).show();
							}
						}
					}

				});

		builder.setNegativeButton(R.string.cancel,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						DialogUtil.closeDialog(dialog, true);
					}
				});
		builder.show();
	}

	private void showAreaFilter() {
		final View layout = getLayoutInflater().inflate(
				R.layout.filter_list_area, null);
		final Spinner spinnerArea = (Spinner) layout
				.findViewById(R.id.spinnerArea);
		String[] area = filterListBiz.loadAreaNames();
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, area);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerArea.setAdapter(adapter);

		final boolean isInsert = (clickedFilter == null);
		if (!isInsert) {
			for (int i = 0; i < area.length; i++) {
				if (area[i].equals(clickedFilter.getName())) {
					spinnerArea.setSelection(i);
					break;
				}
			}
		}

		Builder builder = new Builder(this);
		builder.setTitle("区域");
		builder.setView(layout);
		builder.setPositiveButton(R.string.ok,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int arg1) {
						if (spinnerArea.getSelectedItem() == null) {
							Toast.makeText(getBaseContext(), "请选择省市",
									Toast.LENGTH_SHORT).show();
							return;
						}

						if (isInsert) {
							DialogUtil.closeDialog(dialog, true);

							FilterListVO vo = new FilterListVO();
							vo.setCallState(FilterListVO.STATE_BLOCK);
							vo.setSmsState(FilterListVO.STATE_BLOCK);
							vo.setName(spinnerArea.getSelectedItem().toString());
							vo.setNumber(spinnerArea.getSelectedItem()
									.toString());
							vo.setType(FilterListVO.TYPE_BLACK_AREA);
							if (filterListBiz.insert(vo) >= 0) {
								load();
								Toast.makeText(getBaseContext(),
										R.string.insert_ok, Toast.LENGTH_SHORT)
										.show();
							} else {
								Toast.makeText(getBaseContext(),
										R.string.insert_fail,
										Toast.LENGTH_SHORT).show();
							}
						} else {
							clickedFilter.setNumber(spinnerArea
									.getSelectedItem().toString());
							clickedFilter.setName(spinnerArea.getSelectedItem()
									.toString());
							if (filterListBiz.update(clickedFilter) >= 0) {
								getBaseAdapter().notifyDataSetChanged();
								Toast.makeText(getBaseContext(),
										R.string.insert_ok, Toast.LENGTH_SHORT)
										.show();
							} else {
								Toast.makeText(getBaseContext(),
										R.string.insert_fail,
										Toast.LENGTH_SHORT).show();
							}
						}
					}

				});

		builder.setNegativeButton(R.string.cancel,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						DialogUtil.closeDialog(dialog, true);
					}
				});
		builder.show();
	}

	/*
	 * 手动添加/编辑黑白名单
	 */
	private void showFilterEdit() {
		final View layout = getLayoutInflater().inflate(
				R.layout.filter_list_edit, null);
		final TextView editNumber = (TextView) layout
				.findViewById(R.id.edit_number);
		final TextView editName = (TextView) layout
				.findViewById(R.id.edit_name);
		final boolean isInsert = (clickedFilter == null);
		Builder builder = new Builder(this);
		if (isInsert) {
			// 新增
			builder.setTitle("添加");
		} else {
			// 编辑
			editNumber.setText(clickedFilter.getNumber());
			editName.setText(clickedFilter.getName());
			builder.setTitle("编辑");
		}
		builder.setView(layout);
		builder.setPositiveButton(R.string.ok,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						DialogUtil.closeDialog(dialog, false);

						FilterListActivity context = FilterListActivity.this;
						String number = editNumber.getText().toString();
						int type = (isBlackList ? FilterListVO.TYPE_BLACK
								: FilterListVO.TYPE_WHITE);
						if (ValidationUtil.isNullOrEmpty(number)) {
							Toast.makeText(context, "号码不允许为空",
									Toast.LENGTH_SHORT).show();
							return;
						} else if (!ValidationUtil.IsNumber(number)) {
							Toast.makeText(context, "号码只能是数字",
									Toast.LENGTH_SHORT).show();
							return;
						} else {
							DialogUtil.closeDialog(dialog, true);

							String name = editName.getText().toString();
							if (isInsert) {
								// 新增
								CallInfoVO callInfo = new CallInfoVO();
								callInfo.setNumber(number);
								callInfo.setName(name);
								if (filterListBiz.insert(callInfo, isBlackList) >= 0) {
									// TODO: [优化]更改为不刷新，直接notify的方式
									load();
									Toast.makeText(context, R.string.insert_ok,
											Toast.LENGTH_SHORT).show();
								} else {
									Toast.makeText(context,
											R.string.insert_fail,
											Toast.LENGTH_SHORT).show();
								}
							} else {
								// 编辑
								clickedFilter.setNumber(number);
								clickedFilter.setName(name);
								if (filterListBiz.update(clickedFilter) >= 0) {
									getBaseAdapter().notifyDataSetChanged();
									Toast.makeText(context, R.string.insert_ok,
											Toast.LENGTH_SHORT).show();
								} else {
									Toast.makeText(context,
											R.string.insert_fail,
											Toast.LENGTH_SHORT).show();
								}
							}
						}
					}
				});
		builder.setNegativeButton(R.string.cancel,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						DialogUtil.closeDialog(dialog, true);
					}
				});
		builder.show();
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		switch (requestCode) {
		case REQUEST_CODE_FROM_LOCAL_CONTACTS: // 从本地通信录添加
			
		case REQUEST_CODE_FROM_GROUP_CONTACTS: // 从集团通信录添加
			// try {
			// Bundle b = data.getBundleExtra(Constants.DATA);
			// List<Contact> localContacts = (List<Contact>)
			// b.getSerializable(Constants.CONTACT_LIST);
			// new
			// ImportFilterTask(FilterListActivity.this).execute(localContacts.toArray());
			// } catch (Exception e) {
			// ExceptionHandler.handle(e, "从通信录添加到黑白名单时出错");
			// Toast.makeText(this, "添加失败", Toast.LENGTH_SHORT).show();
			// }
			break;
		}
	}

	/*
	 * 异步加载黑白名单
	 */
	private class FilterListLoadTask extends
			AsyncTask<Void, Integer, ArrayList<FilterListVO>> {
		private boolean isBlackList = true;

		public FilterListLoadTask(boolean isBlackList) {
			this.isBlackList = isBlackList;
		}

		@Override
		protected ArrayList<FilterListVO> doInBackground(Void... params) {
			filterListBiz = new FilterListBusiness();
			return filterListBiz.getFilterList(isBlackList);
		}

		@Override
		protected void onPostExecute(ArrayList<FilterListVO> filters) {
			if (!ValidationUtil.isNullOrEmpty(filters)) {
				setListAdapter(new FilterListAdapter(FilterListActivity.this,
						filters));
			} else {
				setListAdapter(null);
			}
		}
	}

	/*
	 * 异步导入黑白名单（带进度展示）
	 */
	private class ImportFilterTask extends AsyncTask<Object, Integer, Integer> {
		private BaseActivity act;
		private ProgressDialog progressDialog;
		private int count;

		public ImportFilterTask(BaseActivity activity) {
			this.act = activity;
		}

		@Override
		protected void onPreExecute() {
			progressDialog = new ProgressDialog(act);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			progressDialog.setTitle(R.string.processing);
			progressDialog.setMax(100);
			progressDialog.setProgress(0);
			progressDialog
					.setMessage(String.format(
							act.getString(R.string.processing_info),
							String.valueOf(0)));
			progressDialog.setCancelable(true);
			progressDialog.show();
		}

		@Override
		protected Integer doInBackground(Object... contacts) {
			count = contacts.length;
			int succeedCount = 0;
			// for (int i = 0; i < count; i++) {
			// Contact contact = (Contact) contacts[i];
			// CallInfoVO callInfo = new CallInfoVO();
			// callInfo.setNumber(contact.getUserPhone());
			// callInfo.setName(contact.getName());
			// if (filterListBiz.insert(callInfo, isBlackList) >= 0) {
			// succeedCount++;
			// }
			// publishProgress(i * 100 / count);
			// }
			return succeedCount;
		}

		@Override
		protected void onProgressUpdate(Integer... progresses) {
			progressDialog.setProgress(progresses[0]);
			progressDialog.setMessage(String.format(
					act.getString(R.string.processing_info),
					String.valueOf(progresses[0])));
		}

		@Override
		protected void onCancelled() {
			progressDialog.cancel();
		}

		@Override
		protected void onPostExecute(Integer succeedCount) {
			// 隐藏进度对话框
			if (FilterListActivity.this != null
					&& !FilterListActivity.this.isFinishing()) {
				progressDialog.dismiss();
			}
			// 刷新黑白名单数据
			load();
			// 显示提示信息
			String hint = null;
			if (succeedCount == count) {
				hint = StringUtil.format("成功添加{0}个名单", count);
			} else {
				hint = StringUtil.format("添加名单成功{0}个，失败{1}个", succeedCount,
						count - succeedCount);
			}
			Toast.makeText(act, hint, Toast.LENGTH_LONG).show();
		}
	}
}
